"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: registry.py
@DateTime: 2025/07/07
@Docs: 动态权限注册系统
"""

from collections import defaultdict
from typing import Any

from app.utils.logger import logger


class PermissionInfo:
    """权限信息类"""

    def __init__(
        self,
        code: str,
        name: str,
        description: str = "",
        module: str = "",
        resource: str = "",
        action: str = "",
        type: str = "undefined",
    ):
        self.code = code
        self.name = name
        self.description = description
        self.module = module
        self.resource = resource
        self.action = action
        self.type = type

    def to_dict(self) -> dict[str, Any]:
        """转换为字典格式"""
        return {
            "code": self.code,
            "name": self.name,
            "description": self.description,
            "module": self.module,
            "resource": self.resource,
            "action": self.action,
            "type": self.type,
        }


class PermissionRegistry:
    """权限注册器"""

    def __init__(self):
        self._permissions: dict[str, PermissionInfo] = {}
        self._module_permissions: dict[str, set[str]] = defaultdict(set)
        self._endpoint_permissions: dict[str, set[str]] = defaultdict(set)

    def register(
        self,
        code: str,
        name: str,
        description: str = "",
        module: str = "",
        resource: str = "",
        action: str = "",
        type: str = "undefined",
    ) -> None:
        """注册权限"""
        if not all([module, resource, action]):
            raise ValueError(f"权限编码 '{code}' 的 module, resource, action 不能为空")

        if code in self._permissions:
            logger.warning(f"权限已存在，将被覆盖: {code}")

        permission_info = PermissionInfo(
            code=code,
            name=name,
            description=description,
            module=module,
            resource=resource,
            action=action,
            type=type,
        )

        self._permissions[code] = permission_info
        if module:
            self._module_permissions[module].add(code)

        logger.debug(f"注册权限: {code} - {name} (Type: {type})")

    def get_all_permissions(self) -> list[PermissionInfo]:
        """获取所有已注册的权限"""
        return list(self._permissions.values())

    def clear(self) -> None:
        """清空所有注册的权限"""
        self._permissions.clear()
        self._module_permissions.clear()
        self._endpoint_permissions.clear()


# 全局权限注册器实例
permission_registry = PermissionRegistry()
